<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/4/11
 * Time: 18:00
 */

namespace app\common\model;


use app\api\model\TeacherEssay;
use app\common\model\app\ConstLinkType;
use think\Db;
use think\db\Query;
use think\Exception;
use think\Model;

/**
 * Class CourseBindService
 * @package app\common\model
 *
 * @property integer curriculum_id
 * @property integer bind_column_id
 * @property boolean online_course
 * @property boolean fupan_answer
 * @property boolean exclusive_group
 * @property boolean stock_analysis_report
 * @property integer expired
 * @property boolean article_reference
 * @property boolean article_report
 *
 */
class CourseBindService extends Model
{
    protected $table = 'course_bind_service';
    protected $pk = 'curriculum_id';

    const FIELDS = [
        'curriculum_id',
        'bind_column_id',
        'online_course',
        'fupan_answer',
        'exclusive_group',
        'stock_analysis_report',
        'expired',
        'expired',
        'article_reference',
        'article_report',
    ];

    const UNIT = 3600 * 24;

    const TEXT = [
        'bind_column_id' => ['title'=>'名师专栏','intro'=>'每天十分钟，对市场未来风险和机会进行战法技术讲解点评','type'=>ConstLinkType::LINK_TYPE_COLUMN],
        'online_course' => ['title'=>'线上课程（每周一次）','intro'=>'系统化的总结本周盘面走势和对未来新方向的解读','type'=>ConstLinkType::LINK_TYPE_NULL],
        'fupan_answer' => ['title'=>'复盘解惑（每周一次）','intro'=>'集中为各大股民解决股市中的疑惑，提供清晰的投资思路','type'=>ConstLinkType::LINK_TYPE_NULL],
        'exclusive_group' => ['title'=>'专属群服务','intro'=>'汇集股市精英，打造高端股票学习交流社区，随时随地学炒股','type'=>ConstLinkType::LINK_TYPE_NULL],
        'stock_analysis_report' => ['title'=>'个股分析报告','intro'=>'板块龙头股深度解析，挖掘板块新龙头投资机会','type'=>ConstLinkType::LINK_TYPE_NULL],
        'article_reference' => ['title'=>'内参','intro'=>'暂无','type'=>ConstLinkType::LINK_TYPE_ESSAY],
        'article_report' => ['title'=>'研报','intro'=>'暂无','type'=>ConstLinkType::LINK_TYPE_ESSAY],
    ];

    public static function insertOrUpdate($data) {
        $params = [];
        foreach (self::FIELDS as $FIELD) {
            if (array_key_exists($FIELD, $data)) {
                $params[$FIELD] = $data[$FIELD];
            } else {
                throw new Exception("'$FIELD'字段必须存在");
            }
        }
        $sql = <<<SQL
INSERT INTO course_bind_service (curriculum_id, bind_column_id, online_course, fupan_answer, exclusive_group, stock_analysis_report, expired, article_reference, article_report) VALUES 
(:curriculum_id, :bind_column_id, :online_course, :fupan_answer, :exclusive_group, :stock_analysis_report, :expired, :article_reference, :article_report)
ON CONFLICT (curriculum_id) DO UPDATE SET 
bind_column_id=:bind_column_id, online_course=:online_course, fupan_answer=:fupan_answer, exclusive_group=:exclusive_group, stock_analysis_report=:stock_analysis_report, expired=:expired, article_reference=:article_reference, article_report=:article_report
RETURNING *
SQL;
        $result = Db::query($sql, $params);
        $model = new self();
        $model->data($result);
        return $model;
    }

    /**
     * 获取可用的服务
     *
     * @param $uid
     * @param $cid
     * @return static
     */
    public static function getEnableService($uid, $cid) {
        $service = self::get(function (Query $query) use ($uid, $cid) {
            $query->alias('s')->join('user_buy_curriculum b','b.uc_curriculum=s.curriculum_id');
            $query->where('b.uc_user','=', $uid);
            $query->where('s.curriculum_id','=', $cid);
            $query->where('b.service_expired','>', time());
            $query->field('s.*,b.service_expired');
        });
        return $service;
    }

    /**
     * 获取可用服务列表
     *
     * @return array
     */
    public function getServiceData($courseId) {
        if (empty($this->service_expired)) {
            $data = [
                [
                    'title' => '服务期限',
                    'intro' => "{$this->expired}天",
                    'type' => 0,
                ]
            ];
        } else {
            $expired = date('Y-m-d', $this->service_expired);
            $data = [
                [
                    'title' => '服务期限',
                    'intro' => "{$expired}",
                    'type' => 0,
                ]
            ];
        }
        foreach (self::TEXT as $key => $obj) {
            if ($this->$key) {
                if ($obj['type']) {
                    $obj['data'] = $this->$key;
                }

                // zk20180525 新增课程服务类型数据处理
                switch ($key) {
                    case 'article_reference':
                        $catalog_id = intval(config('course_serivce.internalReferenceId'));
                        // $obj['catalog_id'] = intval(config('course_serivce.internalReferenceId'));
                        if ($obj['type']==5) $obj['data'] = $catalog_id;
                        $obj['list'] = TeacherEssay::getBindCourseArticle($catalog_id, $courseId, 5);
                        break;
                    case 'article_report':
                        $catalog_id = intval(config('course_serivce.researchReportId'));
                        // $obj['catalog_id'] = intval(config('course_serivce.researchReportId'));
                        if ($obj['type']==5) $obj['data'] = $catalog_id;
                        $obj['list'] = TeacherEssay::getBindCourseArticle($catalog_id, $courseId, 5);
                        break;
                    default :
                }

                $data[] = (object)$obj;
            }
        }
        return $data;
    }

    /**
     * 获取配置的秒数
     *
     * @return int
     */
    public function getSeconds() {
        return $this->expired * self::UNIT;
    }

}